package top.huxy.qqbot.framework;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import top.huxy.qqbot.acks.Ack;
import top.huxy.qqbot.message.At;
import top.huxy.qqbot.message.Image;
import top.huxy.qqbot.message.Message;
import top.huxy.qqbot.message.Text;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author HuXY
 */
public interface EventHandler {
    /**
     * 创建socket时出错
     */
    default void onSocketInitException(Exception e, NodeQQSession session) {
        sleep(1000);
        session.createSocket();
    }

    /**
     * 获取Socket的InputStream时出错
     */
    default void onSocketGetInputStreamException(IOException e, NodeQQSession session) {
        sleep(1000);
        session.createSocket();
    }

    default void onReadInputStreamException(IOException e, NodeQQSession session) {
        sleep(1000);
        session.createSocket();
    }

    /**
     * 收到消息，并分发消息
     */
    default void onMessage(byte[] data, NodeQQSession session) {
        String msg = new String(data);
        JSONObject jsonObject = JSONObject.parseObject(msg);
        if (jsonObject.containsKey("isSystemInfo")) {
            //系统消息
            String msg1 = jsonObject.getString("msg");
            onSystemMessage(msg1);
        } else if (jsonObject.containsKey("message_type")) {
            String messageType = jsonObject.getString("message_type");
            if ("group".equalsIgnoreCase(messageType)) {
                //处理群消息
                GroupMessage groupMessage = parseGroupMessage(jsonObject);
                onGroupMessage(groupMessage, session);
            } else if ("private".equalsIgnoreCase(messageType)) {
                //处理私有消息
                PrivateMessage privateMessage = parsePrivateMessage(jsonObject);
                onPrivateMessage(privateMessage, session);
            }
        } else {
            //无法处理的消息
            onUnknownMessage(jsonObject);
        }
    }

    /**
     * 解析私有消息
     * {
     * message_type: 'private',
     * message_id: 'biKJ6AAAEWYLCIW0YfIIEQA=',
     * time: 1643251729,
     * self_id: 2738581984,
     * from_id: 1847757288,
     * raw_message: '你好',
     * message: [ { type: 'text', text: '你好' } ],
     * user_nickname: '立83兮7盖4'
     * }
     */
    default PrivateMessage parsePrivateMessage(JSONObject jsonObject) {
        String message_id = jsonObject.getString("message_id");
        long time = jsonObject.getLongValue("time") * 1000;
        long self_id = jsonObject.getLongValue("self_id");
        long from_id = jsonObject.getLongValue("from_id");
        String raw_message = jsonObject.getString("raw_message");
        String user_nickname = jsonObject.getString("user_nickname");
        JSONArray messageJsonArray = jsonObject.getJSONArray("message");
        List<Message> messages = new ArrayList<>();
        for (Object o : messageJsonArray) {
            Message item;
            if (o instanceof JSONObject) {
                item = parseReceiveMessageFromJsonObject((JSONObject) o);
            } else {
                item = parseReceiveMessageFromNotJsonObject(o);
            }
            messages.add(item);
        }

        return new PrivateMessage(message_id, time, self_id, from_id, raw_message, user_nickname, messages);
    }

    /**
     * 解析群消息
     * {
     * message_type: 'group',
     * message_id: 'LRm0lG4iiegAAANn9m3JFmHx/XQB',
     * user_id:1847757288,
     * time: 1643249012,
     * self_id: 2738581984,
     * group_id: 756659348,
     * group_name: '测试群',
     * atme: false,
     * raw_message: '测试群消息',
     * message: [ { type: 'text', text: '测试群消息' } ]
     * }
     */
    default GroupMessage parseGroupMessage(JSONObject jsonObject) {
        String message_id = jsonObject.getString("message_id");
        long user_id = jsonObject.getLongValue("user_id");
        long time = jsonObject.getLongValue("time") * 1000;
        long self_id = jsonObject.getLongValue("self_id");

        long groupId = jsonObject.getLongValue("group_id");
        String group_name = jsonObject.getString("group_name");
        boolean atme = jsonObject.getBooleanValue("atme");
        String raw_message = jsonObject.getString("raw_message");
        JSONArray messageJsonArray = jsonObject.getJSONArray("message");
        List<Message> messages = new ArrayList<>();
        for (Object o : messageJsonArray) {
            Message item;
            if (o instanceof JSONObject) {
                item = parseReceiveMessageFromJsonObject((JSONObject) o);
            } else {
                item = parseReceiveMessageFromNotJsonObject(o);
            }
            if (item != null) {
                messages.add(item);
            }
        }

        return new GroupMessage(message_id, user_id, time, self_id, groupId, group_name, atme, raw_message, messages);
    }

    /**
     * 解析o成Message
     *
     * @param o 不是JSONObject，很有可能是包装类型或String
     */
    default Message parseReceiveMessageFromNotJsonObject(Object o) {
        System.err.println("can't parse Object,type=:" + o.getClass().toString() + ",o=" + o.toString());
        return null;
    }

    /**
     * 解析o成Message
     *
     * @param o 是个JSONObject
     */
    default Message parseReceiveMessageFromJsonObject(JSONObject o) {
        String type = o.getString("type");
        if ("text".equals(type)) {
            String text = o.getString("text");
            return new Text(text);
        } else if ("at".equals(type)) {
            long qq = o.getLongValue("qq");
            String text = o.getString("text");
            return new At(qq, text);
        } else if ("image".equals(type)) {
            String url = o.getString("url");
            return new Image(url);
        }
        System.err.println("can't parse type:" + type + ",o=" + o.toJSONString());
        return null;
    }

    /**
     * 处理未知消息
     */
    default void onUnknownMessage(JSONObject msg) {
        System.err.println("无法处理的msg=" + msg.toJSONString());
    }

    /**
     * 收到私有消息
     */
    default void onPrivateMessage(PrivateMessage privateMessage, NodeQQSession session) {
    }

    /**
     * 收到群消息
     */
    default void onGroupMessage(GroupMessage groupMessage, NodeQQSession session) {
    }

    /**
     * 收到系统消息
     */
    default void onSystemMessage(String msg1) {
    }

    /**
     * 发送消息时异常
     */
    default void onSendMessageException(IOException e, NodeQQSession session, Ack ack) {
    }

    /**
     * 发送消息前的钩子
     *
     * @param ack 即将发送的消息
     */
    default void beforeSendMessage(Ack ack) {
    }

    /**
     * 发送消息后的钩子
     *
     * @param ack 已发送的消息
     */
    default void afterSendMessage(Ack ack) {
        try {
            Thread.sleep(100L);
        } catch (InterruptedException ignored) {
        }
    }

    /**
     * 创建Socket连接时的钩子
     */
    default void beforeCreateSocket(String ip, int port) {
    }

    /**
     * 创建Socket后，将进行登录，在登录之前的钩子
     */
    default void beforeQQLogin(long qq, String pwd) {
    }

    /**
     * 线程睡眠
     */
    default void sleep(long n) {
        try {
            Thread.sleep(n);
        } catch (InterruptedException ignored) {
        }
    }

    /**
     * 调用onMessage前的钩子
     */
    default void beforeHandlerMessage() {
    }

    /**
     * 调用onMessage后的钩子
     */
    default void afterHandlerMessage() {
    }

    default void afterCreateSocket(NodeQQSession nodeQQSession){}
}
